const express = require('express');
const router = express.Router();
const { Weather, WeatherForecast } = require('../models');
const { Op } = require('sequelize');

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// GET /api/weather - 获取天气信息
router.get('/', async (req, res) => {
  try {
    const { city, location } = req.query;
    
    // 模拟网络延迟
    await delay(500);
    
    let whereClause = {};
    
    // 根据城市名查询
    if (city) {
      whereClause.city = {
        [Op.like]: `%${city}%`
      };
    }
    
    // 查询实时天气数据
    const weatherData = await Weather.findOne({
      where: whereClause,
      order: [['reporttime', 'DESC']]
    });
    
    // 查询天气预报数据
    const forecastData = await WeatherForecast.findAll({
      where: whereClause,
      order: [['date', 'ASC']],
      limit: 7
    });
    
    if (!weatherData) {
      return res.status(404).json({
        success: false,
        message: '未找到天气数据'
      });
    }
    
    // 构造返回数据
    const response = {
      success: true,
      data: {
        city: weatherData.city,
        adcode: weatherData.adcode,
        province: weatherData.province,
        reporttime: weatherData.reporttime,
        lives: [{
          province: weatherData.province,
          city: weatherData.city,
          adcode: weatherData.adcode,
          weather: weatherData.weather,
          temperature: weatherData.temperature,
          winddirection: weatherData.winddirection,
          windpower: weatherData.windpower,
          humidity: weatherData.humidity,
          reporttime: weatherData.reporttime
        }],
        casts: forecastData.map(forecast => ({
          date: forecast.date,
          week: forecast.week,
          dayweather: forecast.dayweather,
          nightweather: forecast.nightweather,
          daytemp: forecast.daytemp,
          nighttemp: forecast.nighttemp,
          daywind: forecast.daywind,
          nightwind: forecast.nightwind,
          daypower: forecast.daypower,
          nightpower: forecast.nightpower
        }))
      },
      message: '获取天气信息成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('天气API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取天气信息失败',
      error: error.message
    });
  }
});

// GET /api/weather/forecast - 获取天气预报
router.get('/forecast', async (req, res) => {
  try {
    const { city, days = 7 } = req.query;
    
    await delay(300);
    
    let whereClause = {};
    if (city) {
      whereClause.city = {
        [Op.like]: `%${city}%`
      };
    }
    
    const forecastData = await WeatherForecast.findAll({
      where: whereClause,
      order: [['date', 'ASC']],
      limit: parseInt(days)
    });
    
    const response = {
      success: true,
      data: {
        city: forecastData[0]?.city || city || '广州市',
        forecast: forecastData.map(forecast => ({
          date: forecast.date,
          weather: forecast.dayweather,
          temperature: {
            min: parseInt(forecast.nighttemp),
            max: parseInt(forecast.daytemp)
          },
          humidity: 60 + Math.floor(Math.random() * 20),
          wind: forecast.daywind
        }))
      },
      message: '获取天气预报成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('天气预报API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取天气预报失败',
      error: error.message
    });
  }
});

// GET /api/weather/current - 获取实时天气
router.get('/current', async (req, res) => {
  try {
    const { location } = req.query;
    
    await delay(200);
    
    // 这里可以根据location查询最近的天气数据
    // 简化处理，返回最新的天气数据
    const currentData = await Weather.findOne({
      order: [['reporttime', 'DESC']]
    });
    
    if (!currentData) {
      return res.status(404).json({
        success: false,
        message: '未找到实时天气数据'
      });
    }
    
    const response = {
      success: true,
      data: {
        location: location || '113.289405,23.013125',
        weather: currentData.weather,
        temperature: parseInt(currentData.temperature),
        feels_like: parseInt(currentData.temperature) + 2,
        humidity: parseInt(currentData.humidity),
        pressure: 1013,
        visibility: 10000,
        wind: {
          speed: parseInt(currentData.windpower),
          direction: currentData.winddirection,
          degree: 135
        },
        update_time: currentData.reporttime
      },
      message: '获取实时天气成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('实时天气API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取实时天气失败',
      error: error.message
    });
  }
});

module.exports = router; 